package cn.ava.ymcc.security;

import cn.ava.ymcc.dto.LoginTokenInfoDto;
import cn.ava.ymcc.domain.Login;
import cn.ava.ymcc.domain.Permission;
import cn.ava.ymcc.mapper.PermissionMapper;
import cn.ava.ymcc.service.ILoginService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Security加载登录人信息和权限信息的 service
 */
@Component
public class LoginUserDetailsService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.登录人信息
        Wrapper<Login> query = new EntityWrapper<>();
        query.eq("username",username);
        Login login = loginService.selectOne(query);
        if(login != null){//查到了包装权限信息
            //2.权限信息
            List<Permission> permissionList = permissionMapper.loadPermissionByLoginId(login.getId());
            // Permission  -->  GrantedAuthority
            List<SimpleGrantedAuthority> authorities = permissionList.stream().map(p -> new SimpleGrantedAuthority(p.getSn())).collect(Collectors.toList());
            // 返回用户信息(封装loginId与username)
            return new User(JSON.toJSONString(new LoginTokenInfoDto(login.getId(), login.getUsername())),login.getPassword(),
                    login.getEnabled(),login.getAccountNonExpired(),login.getCredentialsNonExpired(),
                    login.getAccountNonLocked(),authorities);
        }
        return null;//查不到返回null
    }

}